package com.ebeitech.doorapp.view.homepage;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.domain.AppInfo;
import com.ebeitech.doorapp.domain.dao.AppInfoDao;
import com.ebeitech.doorapp.http.EbeiErrorCode;
import com.ebeitech.doorapp.http.HttpListener;
import com.ebeitech.doorapp.http.HttpService;
import com.ebeitech.doorapp.http.model.BaseModel;
import com.ebeitech.doorapp.http.service.HttpOperateServiceRx;
import com.ebeitech.doorapp.util.image.GlideRoundTransform;
import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.doorapp.view.CordovaBaseActivity;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.ui.CommonTitleBar;
import com.ebeitech.library.ui.dialog.CommonAlertDialogFragment;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshBase;
import com.ebeitech.library.ui.pulltorefresh.PullToRefreshListView;
import com.ebeitech.library.util.CommonUtil;
import com.ebeitech.library.util.FileUtil;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.StringUtil;
import com.ebeitech.library.util.ViewUtil;
import com.ebeitech.library.util.ZipUtil;
import com.google.gson.Gson;

import org.json.JSONArray;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.ResponseBody;
import retrofit2.Call;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import static com.tencent.qalsdk.service.QalService.context;

/**
 * Created by alice on 2017/11/1.
 */
public class AppListActivity extends BaseActivity {

	@BindView(R.id.tvTitle)
	TextView mTitleView;
	@BindView(R.id.view_title)
	CommonTitleBar mTitleBarView;
	@BindView(R.id.listView)
	PullToRefreshListView mPullToRefreshView;
	ListView mListView;

	private Context mContext;
	private APPListAdapter mAdapter;
	private List<ContentItem> mDatas = new ArrayList<ContentItem>();

	private String mUserId;

	private HttpService mHttpService;
	private CommonAlertDialogFragment mProgressDialog;
	private boolean isRefreshing;

	@Override
	protected void onCreate(Bundle arg0) {
		if (arg0 == null) {
			arg0 = new Bundle();
		}
		arg0.putBoolean(SPConstants.IS_FIT_STATUS_BAR, false);
		super.onCreate(arg0);
		setContentView(R.layout.ebei_activity_pulltorefreshlistview);
		ButterKnife.bind(this);
		mContext = this;
		mUserId = StringUtil.getDefaultString(SPManager.getInstance(mContext).get(SPConstants.USER_ID, ""));
		mHttpService = HttpService.getInstance();

		initView();
		loadAppList();
	}

	private void initView() {
		mTitleView.setText("应用");
		mTitleBarView.setBtnBackVisible(false);

		mListView = mPullToRefreshView.getRefreshableView();
		mPullToRefreshView.setScrollLoadEnabled(false);
		mPullToRefreshView.setPullRefreshEnabled(true);
		mPullToRefreshView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
				if (!isRefreshing) {
					isRefreshing = true;
					loadAppList();
				} else {
					mPullToRefreshView.onPullDownRefreshComplete();
				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

			}
		});
		mAdapter = new APPListAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setBackgroundResource(R.color.ebei_activity_bg);
		mListView.setDivider(null);
	}

	private void loadAppList() {
		HttpOperateServiceRx mHttpOperateServiceRx = mHttpService.getRxGsonRetrofit().create(HttpOperateServiceRx.class);
		final Call<ResponseBody> call = mHttpOperateServiceRx.doLoadAppList();
		final CommonAlertDialogFragment mProgressDialog = ViewUtil.showProgressDialog(mContext);
		mHttpService.executeHttp(mContext, call, new HttpListener<BaseModel>() {

			private List<ContentItem> datas = new ArrayList<ContentItem>();

			@Override
			public void onDoInBackground(BaseModel result) {
				super.onDoInBackground(result);
				Map<String, List<AppInfo>> map = new HashMap<>();
				try {
					if (result != null) {
						Object retData = result.getRetData();
						JSONArray jsonArray = new JSONArray(new Gson().toJson(retData));
						for (int i = 0; i < jsonArray.length(); i++) {
							AppInfo appInfo = new AppInfo();
							appInfo.initWithJson(jsonArray.optString(i));

							List<AppInfo> appInfos = map.get(appInfo.getGroupId());
							if (appInfos == null) {
								appInfos = new ArrayList<AppInfo>();
								map.put(appInfo.getGroupId(), appInfos);

								ContentItem item = new ContentItem();
								item.setGroupName(appInfo.getGroupName());
								item.setAppInfos(appInfos);
								datas.add(item);
							}
							appInfos.add(appInfo);
						}
					}
				} catch (Exception e) {}
			}

			@Override
			public void onError(EbeiErrorCode errorCode) {
				ViewUtil.dismissDialog(mProgressDialog);

				isRefreshing = false;
				mPullToRefreshView.onPullDownRefreshComplete();
			}

			@Override
			public void onSuccess(BaseModel result) {
				ViewUtil.dismissDialog(mProgressDialog);

				mDatas.clear();
				mDatas.addAll(datas);
				mAdapter.notifyDataSetChanged();
				isRefreshing = false;
				mPullToRefreshView.onPullDownRefreshComplete();
			}
		}, BaseModel.class, false);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1) {
			SPManager.getInstance(mContext).put(SPConstants.APP_ID, "");
		}
	}

	class APPListAdapter extends BaseAdapter {

		private int margin;
		private int itemWidth;

		public APPListAdapter() {
			margin = ViewUtil.dp2px(mContext, 10);
		}

		@Override
		public int getCount() {
			return mDatas.size();
		}

		@Override
		public Object getItem(int position) {
			return mDatas.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.ebei_view_list_title_item, null);
				viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
				viewHolder.viewContent = (LinearLayout) convertView.findViewById(R.id.view_content);
				convertView.findViewById(R.id.view_divider).setVisibility(View.VISIBLE);
				viewHolder.viewContent.setVisibility(View.VISIBLE);
				viewHolder.viewContent.setPadding(0, margin, 0, margin);
				convertView.setTag(viewHolder);
				if (itemWidth == 0) {
					itemWidth = (ViewUtil.getScreenSize((Activity) mContext).widthPixels - ViewUtil.dp2px(mContext, 20)) / 4;
				}
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			ContentItem contentItem = mDatas.get(position);
			viewHolder.tvName.setText(contentItem.getGroupName());
			List<AppInfo> appInfos = contentItem.getAppInfos();
			LinearLayout parentView = null;
			viewHolder.viewContent.removeAllViews();
			for (int i = 0; i < appInfos.size(); i++) {
				final AppInfo appInfo = appInfos.get(i);
				if (i % 4 == 0) {
					parentView = new LinearLayout(mContext);
					LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
					if (i > 3) {
						lp.setMargins(0, margin, 0, 0);
					}
					parentView.setLayoutParams(lp);
					viewHolder.viewContent.addView(parentView);
				}
				LinearLayout itemView = new LinearLayout(mContext);
				itemView.setOrientation(LinearLayout.VERTICAL);
				itemView.setGravity(Gravity.CENTER_HORIZONTAL);
				ImageView appLogoImage = new ImageView(mContext);
				int width = ViewUtil.getScreenSize(AppListActivity.this).widthPixels / 4 / 2;
				LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width, width);
				itemView.addView(appLogoImage, lp);
				appLogoImage.measure(0, 0);
				if (!StringUtil.isStringNullOrEmpty(appInfo.getAppLogo())) {
					Glide.with(mContext).load(appInfo.getAppLogo()).placeholder(R.color.ebei_transparent).transform(new GlideRoundTransform(mContext)).into(appLogoImage);
				}

				TextView textView = new TextView(mContext);
				textView.setGravity(Gravity.CENTER_HORIZONTAL);
				textView.setText(appInfo.getAppName());
				textView.setTextColor(getResources().getColor(R.color.ebei_black));
				textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.ebei_common_small_text_size));
				textView.setPadding(0, margin / 2, 0, 0);
				itemView.addView(textView);
				itemView.setLayoutParams(new LinearLayout.LayoutParams(itemWidth, LinearLayout.LayoutParams.WRAP_CONTENT));
				parentView.addView(itemView);

				itemView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						if (AppInfo.APP_TYPE_ONLINE.equals(appInfo.getAppType())) {
							Intent intent = new Intent(mContext, CordovaBaseActivity.class);
							intent.putExtra("url", appInfo.getAppUrl());
							SPManager.getInstance(mContext).put(SPConstants.APP_ID, appInfo.getAppId());
							startActivityForResult(intent, 1);
							return;
						}

						// 判断是否已下载
						boolean isLoad = false;
						String saveFile = CommonUtil.getAppLoadFile(mContext, appInfo.getAppId());
						String downloadFile = CommonUtil.getCacheFile(mContext) + File.separator + appInfo.getAppId() + ".zip";
						String fileFile = saveFile + File.separator + "index.html";
						isLoad = FileUtil.fileExist(fileFile);
						if (true) {
							isLoad = true;
							try {
								ZipUtil.unzip(downloadFile, saveFile, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
						if (isLoad) {
							// 打开APP
							openUrl(appInfo);
						} else {
							if (!isFinishing()) {
								mProgressDialog = ViewUtil.showProgressDialog(mContext);
							}
							// 下载APP
							FileUtil.deleteFile(saveFile);
							FileUtil.deleteFile(downloadFile);
							mHttpService.downloadFile(mContext, new HttpListener<String>() {
								@Override
								public void onStart() {

								}

								@Override
								public void onDoInBackground(String result) {
									super.onDoInBackground(result);
									String downloadFile = CommonUtil.getCacheFile(mContext) + File.separator + appInfo.getAppId() + ".zip";
									String saveFile = CommonUtil.getAppLoadFile(mContext);
									try {
										ZipUtil.unzip(downloadFile, saveFile, false);
									} catch (Exception e) {
										e.printStackTrace();
									}
									AppInfoDao.getInstance().insertOrUpdate(appInfo);
								}

								@Override
								public void onError(EbeiErrorCode errorCode) {
									if (!isFinishing()) {
										ViewUtil.dismissDialog(mProgressDialog);
									}
								}

								@Override
								public void onSuccess(String result) {
									if (!isFinishing()) {
										ViewUtil.dismissDialog(mProgressDialog);
									}
									openUrl(appInfo);
								}
							}, null, appInfo.getAppUrl(), downloadFile);
						}
					}
				});
			}

			return convertView;
		}

		class ViewHolder {
			TextView tvName;
			ViewGroup viewContent;
		}
	}

	private void openUrl(AppInfo appInfo) {
		if (!isFinishing()) {
			mProgressDialog = ViewUtil.showProgressDialog(mContext);
		}
		Observable.create(new Observable.OnSubscribe<String>() {
			@Override
			public void call(Subscriber<? super String> subscriber) {
				String url = "";
				if (appInfo != null) {
					String saveFile = CommonUtil.getAppLoadFile(mContext, appInfo.getAppId());
					String fileFile = saveFile + File.separator + "index.html";
					if (FileUtil.fileExist(fileFile)) {
						url = "file://" + fileFile;
					}
				}
				subscriber.onNext(url);
				subscriber.onCompleted();
			}
		}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new Observer<String>() {
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {

			}

			@Override
			public void onNext(String url) {
				if (!isFinishing()) {
					ViewUtil.dismissDialog(mProgressDialog);
				}
				if (!StringUtil.isStringNullOrEmpty(url)) {
					Intent intent = new Intent(mContext, CordovaBaseActivity.class);
					intent.putExtra("url", url);
					SPManager.getInstance(mContext).put(SPConstants.APP_ID, appInfo.getAppId());
					startActivityForResult(intent, 1);
				}
			}
		});
	}

	class ContentItem {
		private String groupName;
		private List<AppInfo> appInfos;

		public String getGroupName() {
			return groupName;
		}

		public void setGroupName(String groupName) {
			this.groupName = groupName;
		}

		public List<AppInfo> getAppInfos() {
			if (appInfos == null) {
				appInfos = new ArrayList<AppInfo>();
			}
			return appInfos;
		}

		public void setAppInfos(List<AppInfo> appInfos) {
			this.appInfos = appInfos;
		}
	}

}
